package com.qixin.modules.ea.service.impl;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qixin.modules.ea.entity.*;
import com.qixin.modules.ea.mapper.*;
import com.qixin.modules.ea.service.IEaTravelServiceCopy;
import com.qixin.modules.ea.vo.ListPageVo;
import com.qixin.modules.eaApplication.entity.EaBusinessApply;
import com.qixin.modules.eaApplication.mapper.EaBusinessApplyMapper;
import com.qixin.modules.eaBasic.entity.EaTask;
import com.qixin.modules.eaBasic.mapper.EaTaskMapper;
import com.qixin.modules.eaBasic.util.ChangeIdToNameUtil;
import com.qixin.modules.eaBasic.util.WorkFlowUtil;
import com.qixin.modules.eaBasic.vo.EaTaskVo;
import com.qixin.modules.eaLoan.entity.EaLoanbill;
import com.qixin.modules.eaLoan.mapper.EaLoanbillMapper;
import com.qixin.modules.rzInvoice.entity.EaBill;
import com.qixin.modules.rzInvoice.mapper.EaBillMapper;
import com.qixin.modules.rzInvoice.mapper.EaHotelbookspersondMapper;
import com.qixin.modules.rzInvoice.vo.EaCheckInPersonVo;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.Serializable;
import java.util.*;

/**
 * @Description: 差旅费报销单
 * @Author: qixin-boot
 * @Date:   2021-07-06
 * @Version: V1.0
 */
@Service
public class EaTravelServiceImplCopy extends ServiceImpl<EaTravelMapper, EaTravel> implements IEaTravelServiceCopy {

    @Autowired
    private EaHotelbookspersondMapper eaHotelbookspersondMapper;
    @Autowired
    private EaTravelMapper eaTravelMapper;
    @Autowired
    private EaBookDetailMapper eaBookDetailMapper;
    @Autowired
    private EaApplyDetailMapper eaApplyDetailMapper;
    @Autowired
    private EaCostShareMapper eaCostShareMapper;
    @Autowired
    private EaBorrowSubtractMapper eaBorrowSubtractMapper;
    @Autowired
    private EaBillMapper eaBillMapper;
    @Autowired
    private EaTaskMapper eaTaskMapper;
    @Value(value = "${server.fileurl}")
    private String fileurl;
    @Autowired
    private EaLoanbillMapper eaLoanbillMapper;
    @Autowired
    private EaBusinessApplyMapper eaBusinessApplyMapper;
    @Autowired
    private EaCostItemMapper eaCostItemMapper;
    @Autowired
    private ChangeIdToNameUtil changeIdToNameUtil;
    @Autowired
    private WorkFlowUtil workFlowUtil;

    @Override
    @Transactional
    public Map<String,Object> saveMain(EaTravel eaTravel, List<EaBookDetail> eaBookDetailList,List<EaBusinessApply> eaApplyDetailList,List<EaCostShare> eaCostShareList,List<EaBorrowSubtract> eaBorrowSubtractList) {
        Map<String,Object> returnMap = new HashMap<String,Object>();
        Object result = FillRuleUtil.executeRule("travel_code", null);  //获取单据编号
        eaTravel.setBillNo(result.toString());

        String saveType = eaTravel.getSaveType();
        if(saveType.equals("add")) {  //add保存,send提交
            eaTravel.setState(0);   //单据状态:0未提交,1审批中,2已审批,3已退回
        }else{
            eaTravel.setState(1);   //单据状态:0未提交,1审批中,2已审批,3已退回
        }

        eaTravel.setId(Uuid32Util.getUUid());  //主键
        eaTravelMapper.insert(eaTravel);

        //查询差旅费报销单
        //新增待办
        EaTask eaTask = new EaTask();
        eaTask.setId(Uuid32Util.getUUid());
        eaTask.setFormType("1");  //单据类型:1差旅费报销单,2借款单,3还款单,4出差申请单,5出差申请变更单,6招待费申请单,7招待费申请变更单,8招待费报销单,9资金支付审批单,10通讯报销单,11电话记录单
        eaTask.setAuditManId(eaTravel.getAuditManId());   //审批人id
        eaTask.setAuditMan(eaTravel.getAuditMan());    //审批人
        //提交类型:保存:add,提交:send
        if(saveType.equals("add")){  //add保存,send提交
            eaTask.setStatus("0");
        }else{
            eaTask.setStatus("1");
        }
        eaTask.setFormId(eaTravel.getId());    //单据id
        eaTask.setFormCode(eaTravel.getBillNo());   //单据编号
        eaTask.setMemo(eaTravel.getCause());    //备注
        eaTask.setTotalFee(eaTravel.getActualPayAmt()); //总金额
        eaTask.setSort("1");   //排序
        eaTask.setTitle("差旅费报销单");  //标题
        eaTask.setSendManId(eaTravel.getPersonId());    //发送人id
        eaTask.setSendMan(changeIdToNameUtil.getPsnNameById(eaTravel.getPersonId()));    //发送人
        eaTask.setSendDepartId(eaTravel.getDeptId());  //发送人部门id
        eaTask.setSendDepart(changeIdToNameUtil.getNameByDepartId(eaTravel.getDeptId()));   //发送人部门
        eaTask.setSendTime(new Date());    //发送时间
        eaTaskMapper.insert(eaTask);

        if(eaBookDetailList!=null && eaBookDetailList.size()>0) {
            for(EaBookDetail entity:eaBookDetailList) {
                //更新发票使用情况
                String fpid = entity.getFpid();
                EaBill eaBill = eaBillMapper.selectById(fpid);
                String isused = eaBill.getIsused();   //发票是否已使用
                if(isused.equals("1")){
                    throw new RuntimeException("发票号码:" + eaBill.getNumber() + "已被使用!");
                }else{
                    eaBill.setIsused("1");  //设置发票已使用
                    eaBillMapper.updateById(eaBill);
                }

                //外键设置
                entity.setBillId(eaTravel.getId());
                entity.setId(Uuid32Util.getUUid());
                eaBookDetailMapper.insert(entity);
            }
        }
        if(eaApplyDetailList!=null && eaApplyDetailList.size()>0) {
//            for(EaApplyDetail entity:eaApplyDetailList) {
//                //更新出差申请单使用情况
//                String businessApplyId = entity.getBusinessApplyId();
//                EaBusinessApply eaBusinessApply = eaBusinessApplyMapper.selectById(businessApplyId);
//
//
//                    eaBusinessApplyMapper.updateById(eaBusinessApply);
//
//
//                //外键设置
//                entity.setBillId(eaTravel.getId());
//                entity.setId(Uuid32Util.getUUid());
//                eaApplyDetailMapper.insert(entity);
//            }
        }
        if(eaCostShareList!=null && eaCostShareList.size()>0) {
            for(EaCostShare entity:eaCostShareList) {
                //外键设置
                entity.setBillId(eaTravel.getId());
                entity.setId(Uuid32Util.getUUid());
                eaCostShareMapper.insert(entity);
            }
        }
        if(eaBorrowSubtractList!=null && eaBorrowSubtractList.size()>0) {
            for(EaBorrowSubtract entity:eaBorrowSubtractList) {
                //更新借款单使用情况
                String loanBillId = entity.getLoanBillId();
                EaLoanbill eaLoanbill = eaLoanbillMapper.selectById(loanBillId);
                String isused = eaLoanbill.getIsused();   //借款单是否已使用
                if(isused.equals("1")){
                    throw new RuntimeException("借款单:" + eaLoanbill.getBillNo() + "已被使用!");
                }else{
                    eaLoanbill.setIsused("1");  //设置出差申请单已使用
                    //更新借款单信息:来源报销单信息
                    eaLoanbill.setSrcbxbillCode(eaTravel.getBillNo());
                    eaLoanbill.setSrcbxbillPk(eaTravel.getId());
                    eaLoanbill.setSrcbxbillStatus(eaTravel.getState().toString());
                    eaLoanbillMapper.updateById(eaLoanbill);
                }

                //外键设置
                entity.setBillId(eaTravel.getId());
                entity.setId(Uuid32Util.getUUid());
                eaBorrowSubtractMapper.insert(entity);
            }
        }

        returnMap.put("id",eaTravel.getId());
        returnMap.put("code","0");
        returnMap.put("message","保存成功!");
        return returnMap;
    }

    @Override
    @Transactional
    public Map<String,Object> updateMain(EaTravel eaTravel,List<EaBookDetail> eaBookDetailList,List<EaBusinessApply> eaApplyDetailList,List<EaCostShare> eaCostShareList,List<EaBorrowSubtract> eaBorrowSubtractList) {
        Map<String,Object> returnMap = new HashMap<String,Object>();

        //如果picture中有http://localhost:9092/qixin-boot/aaa.png,要处理只保留文件名
        String picture = eaTravel.getPicture() != null ? eaTravel.getPicture().toString() : "";
        String picture_final = picture.replaceAll(fileurl,"");;
        //设置最终的图片如:1111.png,2222.png
        eaTravel.setPicture(picture_final);

        String saveType = eaTravel.getSaveType();
        if(saveType.equals("add")) {  //add保存,send提交
            EaTravel eaTravel1 = eaTravelMapper.selectById(eaTravel.getId());
            eaTravel.setState(eaTravel1.getState());   //单据状态:0未提交,1审批中,2已审批,3已退回
        }else{
            eaTravel.setState(1);   //单据状态:0未提交,1审批中,2已审批,3已退回
        }

        eaTravelMapper.updateById(eaTravel);

        //先将之前的相关发票状态改成未使用
        //获取原费用明细中的发票id
        Map<String,Object> paramsMap = new HashMap<String,Object>();
        paramsMap.put("bill_id",eaTravel.getId());
        List<EaBookDetail> eaBookDetailList1 = eaBookDetailMapper.selectByMap(paramsMap);
        for(EaBookDetail entity:eaBookDetailList1) {
            String fpid = entity.getFpid();  //发票id
            EaBill eaBill = eaBillMapper.selectById(fpid);
            eaBill.setIsused("0");   //设置状态为未使用
            eaBillMapper.updateById(eaBill);
        }

        //获取原费用明细中的出差申请单id
        Map<String,Object> paramsMap2 = new HashMap<String,Object>();
        paramsMap2.put("bill_id",eaTravel.getId());
        List<EaApplyDetail> eaApplyDetailList1 = eaApplyDetailMapper.selectByMap(paramsMap2);
        for(EaApplyDetail entity:eaApplyDetailList1) {
            String fpid = entity.getBusinessApplyId();  //出差申请单id
            EaBusinessApply eaBusinessApply = eaBusinessApplyMapper.selectById(fpid);
         
            eaBusinessApplyMapper.updateById(eaBusinessApply);
        }

        //获取原费用明细中的借款单id
        Map<String,Object> paramsMap3 = new HashMap<String,Object>();
        paramsMap3.put("bill_id",eaTravel.getId());
        List<EaBorrowSubtract> eaBorrowSubtractList1 = eaBorrowSubtractMapper.selectByMap(paramsMap3);
        for(EaBorrowSubtract entity:eaBorrowSubtractList1) {
            String fpid = entity.getLoanBillId();  //借款单id
            EaLoanbill eaLoanbill = eaLoanbillMapper.selectById(fpid);
            eaLoanbill.setIsused("0");   //设置状态为未使用
            eaLoanbillMapper.updateById(eaLoanbill);
        }

        //1.先删除子表数据
        eaBookDetailMapper.deleteByMainId(eaTravel.getId());
        eaApplyDetailMapper.deleteByMainId(eaTravel.getId());
        eaCostShareMapper.deleteByMainId(eaTravel.getId());
        eaBorrowSubtractMapper.deleteByMainId(eaTravel.getId());

        //修改待办
        Map<String,Object> paramsMap4 = new HashMap<String,Object>();
        paramsMap4.put("form_id",eaTravel.getId());
        List<EaTask> eaTaskList = eaTaskMapper.selectByMap(paramsMap4);
        for (EaTask eaTask:eaTaskList) {
            eaTask.setAuditManId(eaTravel.getAuditManId());   //审批人id
            eaTask.setAuditMan(eaTravel.getAuditMan());    //审批人
            //提交类型:保存:add,提交:send
            if(saveType.equals("add")){  //add保存,send提交
                eaTask.setStatus("0");
            }else{
                eaTask.setStatus("1");
            }
            eaTask.setFormId(eaTravel.getId());    //单据id
            eaTask.setFormCode(eaTravel.getBillNo());   //单据编号
            eaTask.setMemo(eaTravel.getCause());    //备注
            eaTask.setTotalFee(eaTravel.getActualPayAmt()); //总金额
            eaTask.setSendManId(eaTravel.getPersonId());    //发送人id
            eaTask.setSendMan(changeIdToNameUtil.getPsnNameById(eaTravel.getPersonId()));    //发送人
            eaTask.setSendDepartId(eaTravel.getDeptId());  //发送人部门id
            eaTask.setSendDepart(changeIdToNameUtil.getNameByDepartId(eaTravel.getDeptId()));   //发送人部门
            eaTask.setSendTime(new Date());    //发送时间
            eaTaskMapper.updateById(eaTask);
        }

        //2.子表数据重新插入
        if(eaBookDetailList!=null && eaBookDetailList.size()>0) {
            for(EaBookDetail entity:eaBookDetailList) {
                //更新发票使用情况
                String fpid = entity.getFpid();
                EaBill eaBill = eaBillMapper.selectById(fpid);
                String isused = eaBill.getIsused();   //发票是否已使用
                if(isused.equals("1")){
                    throw new RuntimeException("发票号码:" + eaBill.getNumber() + "已被使用!");
                }else{
                    eaBill.setIsused("1");  //设置发票已使用
                    eaBillMapper.updateById(eaBill);
                }

                //外键设置
                entity.setBillId(eaTravel.getId());
                entity.setId(Uuid32Util.getUUid());
                eaBookDetailMapper.insert(entity);
            }
        }
//        if(eaApplyDetailList!=null && eaApplyDetailList.size()>0) {
//            for(EaApplyDetail entity:eaApplyDetailList) {
//                //更新出差申请单使用情况
//                String businessApplyId = entity.getBusinessApplyId();
//                EaBusinessApply eaBusinessApply = eaBusinessApplyMapper.selectById(businessApplyId);
//
//
//                    eaBusinessApplyMapper.updateById(eaBusinessApply);
//
//
//                //外键设置
//                entity.setBillId(eaTravel.getId());
//                entity.setId(Uuid32Util.getUUid());
//                eaApplyDetailMapper.insert(entity);
//            }
//        }
        if(eaCostShareList!=null && eaCostShareList.size()>0) {
            for(EaCostShare entity:eaCostShareList) {
                //外键设置
                entity.setBillId(eaTravel.getId());
                entity.setId(Uuid32Util.getUUid());
                eaCostShareMapper.insert(entity);
            }
        }
        if(eaBorrowSubtractList!=null && eaBorrowSubtractList.size()>0) {
            for(EaBorrowSubtract entity:eaBorrowSubtractList) {
                //更新借款单使用情况
                String loanBillId = entity.getLoanBillId();
                EaLoanbill eaLoanbill = eaLoanbillMapper.selectById(loanBillId);
                String isused = eaLoanbill.getIsused();   //借款单是否已使用
                if(isused.equals("1")){
                    throw new RuntimeException("借款单:" + eaLoanbill.getBillNo() + "已被使用!");
                }else{
                    eaLoanbill.setIsused("1");  //设置借款单已使用
                    eaLoanbill.setSrcbxbillCode(eaTravel.getBillNo());
                    eaLoanbill.setSrcbxbillPk(eaTravel.getId());
                    eaLoanbill.setSrcbxbillStatus(eaTravel.getState().toString());
                    eaLoanbillMapper.updateById(eaLoanbill);
                }

                //外键设置
                entity.setBillId(eaTravel.getId());
                entity.setId(Uuid32Util.getUUid());
                eaBorrowSubtractMapper.insert(entity);
            }
        }

        returnMap.put("id",eaTravel.getId());
        returnMap.put("code","0");
        returnMap.put("message","编辑成功!");
        return returnMap;
    }

    @Override
    @Transactional
    public Map<String,Object> delMain(String id) {
        Map<String,Object> retrunMap = new HashMap<String,Object>();

        //差旅费报销单状态为未提交时,可以删除
        EaTravel eaTravel = eaTravelMapper.selectById(id);
        int billStatus = eaTravel.getState();   //单据状态:0时可以删除,其它提示
        if(!(billStatus == 0)){
            retrunMap.put("code","-1");
            retrunMap.put("message","差旅费报销单为未提交时,才能被删除!");
            return retrunMap;
        }

        //获取原费用明细中的出差申请单id
        Map<String,Object> paramsMap2 = new HashMap<String,Object>();
        paramsMap2.put("bill_id",id);
        List<EaApplyDetail> eaApplyDetailList1 = eaApplyDetailMapper.selectByMap(paramsMap2);
        for(EaApplyDetail entity:eaApplyDetailList1) {
            String fpid = entity.getBusinessApplyId();  //出差申请单id
            EaBusinessApply eaBusinessApply = eaBusinessApplyMapper.selectById(fpid);

            eaBusinessApplyMapper.updateById(eaBusinessApply);
        }

        //获取原费用明细中的借款单id
        Map<String,Object> paramsMap3 = new HashMap<String,Object>();
        paramsMap3.put("bill_id",id);
        List<EaBorrowSubtract> eaBorrowSubtractList1 = eaBorrowSubtractMapper.selectByMap(paramsMap3);
        for(EaBorrowSubtract entity:eaBorrowSubtractList1) {
            String fpid = entity.getLoanBillId();  //借款单id
            EaLoanbill eaLoanbill = eaLoanbillMapper.selectById(fpid);
            eaLoanbill.setIsused("0");   //设置状态为未使用
            eaLoanbill.setSrcbxbillCode("");
            eaLoanbill.setSrcbxbillPk("");
            eaLoanbill.setSrcbxbillStatus("");
            eaLoanbillMapper.updateById(eaLoanbill);
        }

        //将相应发票状态改成未使用
        Map<String,Object> paramsMap = new HashMap<String,Object>();
        paramsMap.put("bill_id",id);
        List<EaBookDetail> eaBookDetailList = eaBookDetailMapper.selectByMap(paramsMap);
        if(eaBookDetailList != null && eaBookDetailList.size() > 0){
            for (EaBookDetail eaBookDetail: eaBookDetailList) {
                String fpid = eaBookDetail.getFpid();   //发票id
                EaBill eaBill = eaBillMapper.selectById(fpid);
                eaBill.setIsused("0");  //设置发票未使用
                eaBillMapper.updateById(eaBill);
            }
        }

        //删除相应的待办
//        Map<String,Object> paramaMap = new HashMap<String,Object>();
//        paramaMap.put("form_id",id);
//        List<EaTask> eaTaskList = eaTaskMapper.selectByMap(paramaMap);
//        if(eaTaskList != null && eaTaskList.size() > 0){
//            EaTask eaTask = eaTaskList.get(0);
//
//            //删除相应的工作流
//            workFlowUtil.deleteWorkFlowById(eaTask.getWorkflowTaskId(),eaTask.getProcinstId());
//            eaTaskMapper.deleteById(eaTask.getId());
//        }

        eaBookDetailMapper.deleteByMainId(id);
        eaApplyDetailMapper.deleteByMainId(id);
        eaCostShareMapper.deleteByMainId(id);
        eaBorrowSubtractMapper.deleteByMainId(id);
        eaTravelMapper.deleteById(id);

        retrunMap.put("code","0");
        retrunMap.put("message","删除成功!");
        return retrunMap;
    }

    @Override
    @Transactional
    public void delBatchMain(Collection<? extends Serializable> idList) {
        for(Serializable id:idList) {
            //将相应发票状态改成未使用
            Map<String,Object> paramsMap = new HashMap<String,Object>();
            paramsMap.put("bill_id",id);
            List<EaBookDetail> eaBookDetailList = eaBookDetailMapper.selectByMap(paramsMap);
            if(eaBookDetailList != null && eaBookDetailList.size() > 0){
                for (EaBookDetail eaBookDetail: eaBookDetailList) {
                    String fpid = eaBookDetail.getFpid();   //发票id
                    EaBill eaBill = eaBillMapper.selectById(fpid);
                    eaBill.setIsused("0");  //设置发票未使用
                    eaBillMapper.updateById(eaBill);
                }
            }

            eaBookDetailMapper.deleteByMainId(id.toString());
            eaApplyDetailMapper.deleteByMainId(id.toString());
            eaCostShareMapper.deleteByMainId(id.toString());
            eaBorrowSubtractMapper.deleteByMainId(id.toString());
            eaTravelMapper.deleteById(id);
        }
    }

    //查询差旅费报销单详情
    @Override
    public Map<String,Object> selectById(String id) {
        Map<String,Object> queryWrapper = new HashMap<String,Object>();
        queryWrapper.put("id",id);  //差旅费报销单id
        queryWrapper.put("page",0);
        queryWrapper.put("limit",0);
        List<EaTravel> eaTravelList = eaTravelMapper.selectEaTravels(queryWrapper);
        Map<String,Object> returnMap = new HashMap<String,Object>();

        if(eaTravelList.size() > 0){
            for (EaTravel eaTravel : eaTravelList) {
                Map map = JSON.parseObject(JSON.toJSONString(eaTravel, SerializerFeature.WriteMapNullValue), Map.class);

                if (StrUtil.isNotBlank(map.get("recPersonId").toString())){
                    // 发票归属人 id转名称
                    String recPersonIdName = changeIdToNameUtil.getPsnNameById(map.get("recPersonId").toString());
                    map.put("recPersonIdName",recPersonIdName);
                }

                //格式化时间
                Long billDate = map.get("billDate") != null ? Long.parseLong(map.get("billDate").toString()) : null;
                String billDateStr = DateFormatUtil.formatDateyyMMdd(billDate);
                map.put("billDate",billDateStr);

                //格式化时间
                Long createTime = map.get("createTime") != null ? Long.parseLong(map.get("createTime").toString()) : null;
                String createTimeStr = DateFormatUtil.formatDateyyMMddHHmmss(createTime);
                map.put("createTime",createTimeStr);

                //格式化时间
                Long updateTime = map.get("updateTime") != null ? Long.parseLong(map.get("updateTime").toString()) : null;
                String updateTimeStr = DateFormatUtil.formatDateyyMMddHHmmss(updateTime);
                map.put("updateTime",updateTimeStr);

                //更新时间-用于校验时效性
                map.put("time",updateTimeStr);

                //添加图片
                String picture = map.get("picture") != null ? map.get("picture").toString() : "";
                List<Map<String,Object>> fileList = GetUrlUtil.getUrl(picture,fileurl);

                //添加图片fileList
                map.put("fileList",fileList);

                //添加相应的费用明细
                List<EaBookDetail> eaBookDetailList = eaBookDetailMapper.selectBookDetails(eaTravel.getId());
                List<Map<String,Object>> mapList2 = new ArrayList<Map<String,Object>>();
                if(eaBookDetailList.size() > 0){
                    for (EaBookDetail eaBookDetail: eaBookDetailList) {
                        Map map2 = JSON.parseObject(JSON.toJSONString(eaBookDetail, SerializerFeature.WriteMapNullValue), Map.class);

                        // 发票归属人 id转名称
                        String fygsrName = changeIdToNameUtil.getPsnNameById(eaBookDetail.getFygsr());
                        map2.put("fygsrName",fygsrName);

                        //格式化时间
                        Long kprq = map2.get("kprq") != null ? Long.parseLong(map2.get("kprq").toString()) : null;
                        String kprqStr = DateFormatUtil.formatDateyyMMdd(kprq);
                        map2.put("kprq",kprqStr);

                        //格式化时间
                        Long createTime2 = map2.get("createTime") != null ? Long.parseLong(map2.get("createTime").toString()) : null;
                        String createTimeStr2 = DateFormatUtil.formatDateyyMMddHHmmss(createTime2);
                        map2.put("createTime",createTimeStr2);

                        //格式化时间
                        Long updateTime2 = map2.get("updateTime") != null ? Long.parseLong(map2.get("updateTime").toString()) : null;
                        String updateTimeStr2 = DateFormatUtil.formatDateyyMMddHHmmss(updateTime2);
                        map2.put("updateTime",updateTimeStr2);

                        mapList2.add(map2);
                    }
                }

                //将费用明细加到eaBookDetailList节点
                map.put("eaBookDetailList",mapList2);

                //添加相应的申请单明细
                Map<String, Object> columnMap3 = new HashMap<String, Object>();
                columnMap3.put("bill_id", eaTravel.getId());
                List<EaApplyDetail> eaApplyDetailList = eaApplyDetailMapper.selectByMap(columnMap3);
                List<Map<String,Object>> mapList3 = new ArrayList<Map<String,Object>>();
                if(eaApplyDetailList.size() > 0){
                    for (EaApplyDetail eaApplyDetail: eaApplyDetailList) {
                        Map map3 = JSON.parseObject(JSON.toJSONString(eaApplyDetail, SerializerFeature.WriteMapNullValue), Map.class);

                        //格式化时间
                        Long billDate2 = map3.get("billDate") != null ? Long.parseLong(map3.get("billDate").toString()) : null;
                        String billDate2Str = DateFormatUtil.formatDateyyMMdd(billDate2);
                        map3.put("billDate",billDate2Str);

                        //费用项目
                        EaCostItem eaCostItem = eaCostItemMapper.selectById(EmptyUtil.checkNull(map.get("indexId")));
                        if(eaCostItem != null){
                            map3.put("indexIdName",eaCostItem.getItemName());
                        }

                        mapList3.add(map3);
                    }
                }

                //将申请单明细加到eaApplyDetailList节点
                map.put("eaApplyDetailList",mapList3);

                //添加相应的费用分摊
                Map<String, Object> columnMap4 = new HashMap<String, Object>();
                columnMap4.put("bill_id", eaTravel.getId());
                List<EaCostShare> eaCostShareList = eaCostShareMapper.selectByMap(columnMap4);
                List<Map<String,Object>> mapList4 = new ArrayList<Map<String,Object>>();
                if(eaCostShareList.size() > 0){
                    for (EaCostShare eaCostShare: eaCostShareList) {
                        Map map4 = JSON.parseObject(JSON.toJSONString(eaCostShare, SerializerFeature.WriteMapNullValue), Map.class);
                        mapList4.add(map4);
                    }
                }

                //将费用分摊加到eaCostShareList节点
                map.put("eaCostShareList",mapList4);

                //添加相应的借款单核销
                Map<String, Object> columnMap5 = new HashMap<String, Object>();
                columnMap5.put("bill_id", eaTravel.getId());
                List<EaBorrowSubtract> eaBorrowSubtractList = eaBorrowSubtractMapper.selectByMap(columnMap5);
                List<Map<String,Object>> mapList5 = new ArrayList<Map<String,Object>>();
                if(eaBorrowSubtractList.size() > 0){
                    for (EaBorrowSubtract eaBorrowSubtract: eaBorrowSubtractList) {
                        Map map5 = JSON.parseObject(JSON.toJSONString(eaBorrowSubtract, SerializerFeature.WriteMapNullValue), Map.class);

                        //格式化时间
                        Long loanBillDate = map5.get("loanBillDate") != null ? Long.parseLong(map5.get("loanBillDate").toString()) : null;
                        String loanBillDateStr = DateFormatUtil.formatDateyyMMdd(loanBillDate);
                        map5.put("loanBillDate",loanBillDateStr);

                        //费用项目
                        EaCostItem eaCostItem = eaCostItemMapper.selectById(EmptyUtil.checkNull(map.get("indexId")));
                        if(eaCostItem != null){
                            map5.put("indexIdName",eaCostItem.getItemName());
                        }

                        mapList5.add(map5);
                    }
                }

                //将借款单核销加到eaBorrowSubtractList节点
                map.put("eaBorrowSubtractList",mapList5);
                returnMap = map;
            }
        }
        return returnMap;
    }

    @Override
    @Transactional
    public Map<String, Object> audit(EaTaskVo eaTaskVo) {
        Map<String,Object> returnMap = new HashMap<String,Object>();
        String id = EmptyUtil.checkNull(eaTaskVo.getId());   //单据id
//        String auditManId = EmptyUtil.checkNull(eaTaskVo.getAuditManId());   //审批人id
//        String auditMan = EmptyUtil.checkNull(eaTaskVo.getAuditMan());   //审批人
        String auditComment = EmptyUtil.checkNull(eaTaskVo.getAuditComment());   //审批意见
        int status = eaTaskVo.getStatus();   //单据状态:2通过,3退回

        //获取差旅费报销单-更新状态
        EaTravel eaTravel = eaTravelMapper.selectById(id);
        eaTravel.setState(status);
        eaTravelMapper.updateById(eaTravel);

        Map<String,Object> paramsMap = new HashMap<String,Object>();
        paramsMap.put("form_id",eaTravel.getId());
        List<EaTask> eaTaskList = eaTaskMapper.selectByMap(paramsMap);
        if(eaTaskList != null && eaTaskList.size() > 0){
            EaTask eaTask = eaTaskList.get(0);
            //eaTask.setAuditManId(auditManId);
            //eaTask.setAuditMan(auditMan);
            eaTask.setAuditComment(auditComment);
            eaTask.setStatus(eaTaskVo.getStatus().toString());

            try {
                if((status == 3) || (status == 2)){
                    eaTask.setFinishTime(new Date());   //完成时间

                    //如果是退回操作,要将关联的单据的使用状态变成未使用
                    if(status == 3){
                        List<EaBookDetail> eaBookDetailList = eaBookDetailMapper.selectByMainId(eaTravel.getId());
                        if(eaBookDetailList.size() > 0){
                            for (int i = 0; i < eaBookDetailList.size(); i++) {
                                EaBookDetail eaBookDetail = eaBookDetailList.get(i);
                                EaBill eaBill = eaBillMapper.selectById(eaBookDetail.getFpid());
                                eaBill.setIsused("0");   //更新发票未使用
                                eaBillMapper.updateById(eaBill);
                            }
                        }
                        List<EaApplyDetail> eaApplyDetailList = eaApplyDetailMapper.selectByMainId(eaTravel.getId());
                        if(eaApplyDetailList.size() > 0){
                            for (int i = 0; i < eaApplyDetailList.size(); i++) {
                                EaApplyDetail eaApplyDetail = eaApplyDetailList.get(i);
                                EaBusinessApply eaBusinessApply = eaBusinessApplyMapper.selectById(eaApplyDetail.getBusinessApplyId());

                                eaBusinessApplyMapper.updateById(eaBusinessApply);
                            }
                        }
                        List<EaBorrowSubtract> eaBorrowSubtractList = eaBorrowSubtractMapper.selectByMainId(eaTravel.getId());
                        if(eaBorrowSubtractList.size() > 0){
                            for (int i = 0; i < eaBorrowSubtractList.size(); i++) {
                                EaBorrowSubtract eaBorrowSubtract = eaBorrowSubtractList.get(i);
                                EaLoanbill eaLoanbill = eaLoanbillMapper.selectById(eaBorrowSubtract.getLoanBillId());
                                eaLoanbill.setIsused("0");   //更新借款单未使用
                                eaLoanbillMapper.updateById(eaLoanbill);
                            }
                        }
                    }
                }
                eaTask.setAuditTime(new Date());    //审批时间
                eaTaskMapper.updateById(eaTask);

                returnMap.put("code","0");
                returnMap.put("message","审核成功!");
                return returnMap;
            }catch (Exception e){
                returnMap.put("code","-1");
                returnMap.put("message","系统异常,审核失败!");
                return returnMap;
            }
        }else{
            returnMap.put("code","-1");
            returnMap.put("message","待办不存在!");
            return returnMap;
        }
    }

    //查询差旅费报销单列表
    @Override
    public Map<String, Object> list(ListPageVo listPageVo) {
        LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        Map<String,Object> returnMap = new HashMap<String,Object>();
        String page = EmptyUtil.checkNull(listPageVo.getPage());
        String limit = EmptyUtil.checkNull(listPageVo.getLimit());
        String keyword = EmptyUtil.checkNull(listPageVo.getKeyword());
        String userid = EmptyUtil.checkNull(loginUser.getId());   //用户id
        String status = EmptyUtil.checkNull(listPageVo.getStatus());   //状态
        String billNo = EmptyUtil.checkNull(listPageVo.getBillNo());   //单据编号(pc)
        String billDateBegin = EmptyUtil.checkNull(listPageVo.getBillDateBegin());   //单据日期-开始(pc)
        String billDateEnd = EmptyUtil.checkNull(listPageVo.getBillDateEnd());   //单据日期-结束(pc)
        String personId = EmptyUtil.checkNull(listPageVo.getPersonId());   //申请人/报销人/借款人/还款人(pc)
        String explainStr = EmptyUtil.checkNull(listPageVo.getCasue());   //事由(pc)
        String sysOrgCode = EmptyUtil.checkNull(listPageVo.getSysOrgCode());   //所属组织(pc)

        Map<String,Object> paramsMap = new HashMap<String,Object>();
        String keyword1 = "%" + keyword + "%";
        paramsMap.put("keyword",keyword1);
        paramsMap.put("page",(Integer.parseInt(page) -1) * Integer.parseInt(limit));
        paramsMap.put("limit",Integer.parseInt(limit));
        paramsMap.put("userid",userid);
        paramsMap.put("status",status);
        paramsMap.put("billNo",billNo);
        paramsMap.put("billDateBegin",billDateBegin);
        paramsMap.put("billDateEnd",billDateEnd);
        paramsMap.put("personId",personId);
        paramsMap.put("explainStr",explainStr);
        paramsMap.put("sysOrgCode",sysOrgCode);
        List<EaTravel> eaTravelList = eaTravelMapper.selectEaTravels(paramsMap);

        List<Map<String,Object>> mapList = new ArrayList<Map<String,Object>>();
        if(eaTravelList.size() > 0){
            for (EaTravel eaTravel : eaTravelList) {
                Map map = JSON.parseObject(JSON.toJSONString(eaTravel, SerializerFeature.WriteMapNullValue), Map.class);

                //格式化时间
                Long billDate = map.get("billDate") != null ? Long.parseLong(map.get("billDate").toString()) : null;
                String billDateStr = DateFormatUtil.formatDateyyMMdd(billDate);
                map.put("billDate",billDateStr);

                //格式化时间
                Long createTime = map.get("createTime") != null ? Long.parseLong(map.get("createTime").toString()) : null;
                String createTimeStr = DateFormatUtil.formatDateyyMMddHHmmss(createTime);
                map.put("createTime",createTimeStr);

                //格式化时间
                Long updateTime = map.get("updateTime") != null ? Long.parseLong(map.get("updateTime").toString()) : null;
                String updateTimeStr = DateFormatUtil.formatDateyyMMddHHmmss(updateTime);
                map.put("updateTime",updateTimeStr);

                //更新时间-用于校验时效性
                map.put("time",updateTimeStr);
                mapList.add(map);
            }
        }

        int count = 0;
        paramsMap.put("page",0);
        paramsMap.put("limit",0);
        paramsMap.put("keyword",keyword1);
        paramsMap.put("userid",userid);
        List<EaTravel> list2 = eaTravelMapper.selectEaTravels(paramsMap);
        count = list2.size();

        returnMap.put("records",mapList);
        returnMap.put("total",count);
        return returnMap;
    }

    //查询差旅费报销单详情
    @Override
    public Map<String,Object> queryPrintModelById(String id) {
        Map<String,Object> queryWrapper = new HashMap<String,Object>();
        queryWrapper.put("id",id);  //差旅费报销单id
        queryWrapper.put("page",0);
        queryWrapper.put("limit",0);
        List<EaTravel> eaTravelList = eaTravelMapper.selectEaTravelsForPrint(queryWrapper);

        Map<String,Object> returnMap = new HashMap<String,Object>();

        if(eaTravelList.size() > 0){
            for (EaTravel eaTravel : eaTravelList) {
                Map map = JSON.parseObject(JSON.toJSONString(eaTravel, SerializerFeature.WriteMapNullValue), Map.class);

                //格式化时间
                Long billDate = map.get("billDate") != null ? Long.parseLong(map.get("billDate").toString()) : null;
                String billDateStr = DateFormatUtil.formatDateyyMMdd(billDate);
                map.put("billDate",billDateStr);

                //格式化时间
                Long createTime = map.get("createTime") != null ? Long.parseLong(map.get("createTime").toString()) : null;
                String createTimeStr = DateFormatUtil.formatDateyyMMddHHmmss(createTime);
                map.put("createTime",createTimeStr);

                //格式化时间
                Long updateTime = map.get("updateTime") != null ? Long.parseLong(map.get("updateTime").toString()) : null;
                String updateTimeStr = DateFormatUtil.formatDateyyMMddHHmmss(updateTime);
                map.put("updateTime",updateTimeStr);

                //将报销金额转成中文
                String actualPayAmt = map.get("actualPayAmt") != null ? map.get("actualPayAmt").toString() : "0";
                actualPayAmt = ConvertUpMoneyUtil.toChinese(actualPayAmt);
                map.put("actualPayAmt_cn",actualPayAmt);

                //添加图片
                String picture = map.get("picture") != null ? map.get("picture").toString() : "";
                List<Map<String,Object>> fileList = GetUrlUtil.getUrl(picture,fileurl);

                //添加图片fileList
                map.put("fileList",fileList);

                //添加相应的费用明细
                List<EaBookDetail> eaBookDetailList = eaBookDetailMapper.selectBookDetails(eaTravel.getId());
                List<Map<String,Object>> mapList2 = new ArrayList<Map<String,Object>>();
                List<EaCheckInPersonVo> eaCheckInPersonVoList = new ArrayList<>();
                if(eaBookDetailList.size() > 0){
                    for (EaBookDetail eaBookDetail: eaBookDetailList) {
                        Map map2 = JSON.parseObject(JSON.toJSONString(eaBookDetail, SerializerFeature.WriteMapNullValue), Map.class);

                        //将发票金额转为大写金额
                        String actualEaAmt_cn = map2.get("actualEaAmt") != null ? map2.get("actualEaAmt").toString() : "0";
                        actualEaAmt_cn = ConvertUpMoneyUtil.toChinese(actualEaAmt_cn);
                        map2.put("actualEaAmt_cn",actualEaAmt_cn);

                        //格式化时间
                        Long kprq = map2.get("kprq") != null ? Long.parseLong(map2.get("kprq").toString()) : null;
                        String kprqStr = DateFormatUtil.formatDateyyMMdd(kprq);
                        map2.put("kprq",kprqStr);

                        //格式化时间
                        Long createTime2 = map2.get("createTime") != null ? Long.parseLong(map2.get("createTime").toString()) : null;
                        String createTimeStr2 = DateFormatUtil.formatDateyyMMddHHmmss(createTime2);
                        map2.put("createTime",createTimeStr2);

                        //格式化时间
                        Long updateTime2 = map2.get("updateTime") != null ? Long.parseLong(map2.get("updateTime").toString()) : null;
                        String updateTimeStr2 = DateFormatUtil.formatDateyyMMddHHmmss(updateTime2);
                        map2.put("updateTime",updateTimeStr2);


                        // 判断是否是住宿发票 kind = 3
                        String kind = map2.get("kind").toString();
                        if(kind.equals("3")){
                            String fpid = map2.get("fpid").toString();
                            //查询入住人明细
                            List<EaCheckInPersonVo> eaCheckInPersonVos = eaHotelbookspersondMapper.getByFpid(fpid);
                            for (EaCheckInPersonVo eaCheckInPersonVo:eaCheckInPersonVos) {
                                // 将金额转成中文
                                String cost_cn = eaCheckInPersonVo.getCost() != null? eaCheckInPersonVo.getCost().toString() : "0";
                                eaCheckInPersonVo.setCost_cn(ConvertUpMoneyUtil.toChinese(cost_cn));
                                eaCheckInPersonVoList.add(eaCheckInPersonVo);
                            }
                        }
                        mapList2.add(map2);
                    }
                }

                //将费用明细加到eaBookDetailList节点
                map.put("eaBookDetailList",mapList2);

                //将酒店住宿人明细加到eaHotelbookspersondList 节点
                map.put("eaHotelbookspersondList",eaCheckInPersonVoList);

                //添加相应的申请单明细
                Map<String, Object> columnMap3 = new HashMap<String, Object>();
                columnMap3.put("bill_id", eaTravel.getId());
                List<EaApplyDetail> eaApplyDetailList = eaApplyDetailMapper.selectByMap(columnMap3);
                List<Map<String,Object>> mapList3 = new ArrayList<Map<String,Object>>();
                if(eaApplyDetailList.size() > 0){
                    for (EaApplyDetail eaApplyDetail: eaApplyDetailList) {
                        Map map3 = JSON.parseObject(JSON.toJSONString(eaApplyDetail, SerializerFeature.WriteMapNullValue), Map.class);

                        //格式化时间
                        Long billDate2 = map3.get("billDate") != null ? Long.parseLong(map3.get("billDate").toString()) : null;
                        String billDate2Str = DateFormatUtil.formatDateyyMMdd(billDate2);
                        map3.put("billDate",billDate2Str);

                        //费用项目
                        EaCostItem eaCostItem = eaCostItemMapper.selectById(EmptyUtil.checkNull(map.get("indexId")));
                        if(eaCostItem != null){
                            map3.put("indexIdName",eaCostItem.getItemName());
                        }

                        mapList3.add(map3);
                    }
                }

                //将申请单明细加到eaApplyDetailList节点
                map.put("eaApplyDetailList",mapList3);

                //添加相应的费用分摊
                Map<String, Object> columnMap4 = new HashMap<String, Object>();
                columnMap4.put("bill_id", eaTravel.getId());
                List<EaCostShare> eaCostShareList = eaCostShareMapper.selectByMap(columnMap4);
                List<Map<String,Object>> mapList4 = new ArrayList<Map<String,Object>>();
                if(eaCostShareList.size() > 0){
                    for (EaCostShare eaCostShare: eaCostShareList) {
                        Map map4 = JSON.parseObject(JSON.toJSONString(eaCostShare, SerializerFeature.WriteMapNullValue), Map.class);
                        mapList4.add(map4);
                    }
                }

                //将费用分摊加到eaCostShareList节点
                map.put("eaCostShareList",mapList4);

                //添加相应的借款单核销
                Map<String, Object> columnMap5 = new HashMap<String, Object>();
                columnMap5.put("bill_id", eaTravel.getId());
                List<EaBorrowSubtract> eaBorrowSubtractList = eaBorrowSubtractMapper.selectByMap(columnMap5);
                List<Map<String,Object>> mapList5 = new ArrayList<Map<String,Object>>();
                if(eaBorrowSubtractList.size() > 0){
                    for (EaBorrowSubtract eaBorrowSubtract: eaBorrowSubtractList) {
                        Map map5 = JSON.parseObject(JSON.toJSONString(eaBorrowSubtract, SerializerFeature.WriteMapNullValue), Map.class);

                        //格式化时间
                        Long loanBillDate = map5.get("loanBillDate") != null ? Long.parseLong(map5.get("loanBillDate").toString()) : null;
                        String loanBillDateStr = DateFormatUtil.formatDateyyMMdd(loanBillDate);
                        map5.put("loanBillDate",loanBillDateStr);

                        //费用项目
                        EaCostItem eaCostItem = eaCostItemMapper.selectById(EmptyUtil.checkNull(map.get("indexId")));
                        if(eaCostItem != null){
                            map5.put("indexIdName",eaCostItem.getItemName());
                        }

                        mapList5.add(map5);
                    }
                }

                //将借款单核销加到eaBorrowSubtractList节点
                map.put("eaBorrowSubtractList",mapList5);
                returnMap = map;
            }
        }
        return returnMap;
    }

    @Override
    public EaTravel queryById(String id) {
        return eaTravelMapper.selectById(id);
    }

}
